<?php

namespace App\Http\Controllers\Admin;

use App\DTOS\Admin\CustomerDTO;
use App\Exceptions\ServiceException;
use App\Exports\ExcelExport;
use App\Http\Controllers\Controller;
use App\Models\ChannelCustomer;
use App\Models\Customer;
use App\Models\Game\BanList;
use App\Models\Game\Sale;
use App\Services\ChennalCustomerService;
use App\Services\CustomerService;
use App\Utils\MyLog;
use App\Utils\ResponseUtil;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Http\Request;

class ChannelCustomerController extends Controller
{
    private ChennalCustomerService $chennalCustomerService;
    private Request $request;
    public function __construct(Request $request,ChennalCustomerService $chennalCustomerService)
    {
        $this->chennalCustomerService = $chennalCustomerService;
        $this->request = $request;
    }

    public function paginate() { //table 数据

        $dto = new CustomerDTO($this->request->all());
        $paginate = $this->chennalCustomerService->paginate($dto);
        $data = $paginate->items();
        foreach($data as &$datum){
            $datum['uuid'] = (string)$datum['id'];
        }
        $res = [];
        $res['code'] = 0;
        $res['data'] = $data;
        $res['count'] = $paginate->total();
        return ResponseUtil::json($res);
    }

    public function export(){ //table 数据导出
        $dto = new CustomerDTO($this->request->all());
        $paginate = $this->chennalCustomerService->paginate($dto);
        $excelRows = [
            ['ID','账号','密码','邀请码','手机号码','真实姓名','身份证号','创建时间']
        ];
        foreach($paginate->items() as $datum){
            $excelRows[] = [$datum['id'], $datum['phone'],$datum['password'],$datum['invite_code'],$datum['$mobile'],$datum['real_name'],
                strval($datum['identity_code']),$datum['created_at']
            ];
        }

        $excel = new ExcelExport($excelRows);
        return Excel::download($excel, '渠道用户.xlsx');
    }

    public function detail($id)
    {
        $customer = ChannelCustomer::query()->where('id',$id)->first();
        $customer['password'] = '';
        return ResponseUtil::success($customer);
    }

    public function resetPass($id)
    {
        $password = $this->request->get('password');
        if (!preg_match("/^[a-zA-Z0-9]+$/",$password)){
            return ResponseUtil::error('密码仅支持数字加字母');
        }
        $enPassword = Crypt::encryptString($password);
        ChannelCustomer::query()->where('id',$id)->update(['password'=>$enPassword]);
        return ResponseUtil::success();
    }

    public function edit($id)
    {

        $mobile = $this->request->get('mobile');
        $identity_code = $this->request->get('identity_code');
        $real_name = $this->request->get('real_name');
        $invite_code = $this->request->get('invite_code');
        $ids = $this->request->get('customer_id');
        MyLog::info('查看传入的ID'.json_encode($ids));
        $customer = Sale::query()->where('code',$invite_code)->first();

        if(!$customer&&!$real_name){
            return ResponseUtil::error('邀请码不存在');
        }
        $updateData = [];
        $customerUd= [];
        if (!empty($mobile)) {
            $updateData['mobile'] = $mobile;
        }
        if (!empty($invite_code)) {
            $updateData['invite_code'] = $invite_code;
            $customerUd['invite_code'] = $invite_code;
        }
        if (!empty($identity_code)) {
            $updateData['identity_code'] = $identity_code;
        }

        if (!empty($real_name)) {
            $updateData['real_name'] = $real_name;
        }

        if (!empty($updateData)) {
            if (strpos($ids, ',') !== false) {
                $idArray = explode(',', $ids);
                ChannelCustomer::query()->whereIn('id', $idArray)->update($updateData);
            }else{
                MyLog::info('查看传入的ID1'.json_encode($id));
                MyLog::info('查看传入的ID'.json_encode($ids));
                ChannelCustomer::query()->where('id', $id)->update($updateData);
                Customer::query()->where('channel_uuid',$id)->update($customerUd);
            }
        }
        return ResponseUtil::success();
    }

    public function showPass($id)
    {
        try{
            $customer = ChannelCustomer::query()->find($id);

            $enPassword = data_get($customer,'password');
            return ResponseUtil::success(['password'=>Crypt::decryptString($enPassword)]);
        }catch(\Exception $e){
            return ResponseUtil::error($e->getMessage());
        }
    }

    public function autoGen()
    {
        $data = request()->only(['number','prefix','password']);
        $number = (int)data_get($data,'number');
        $prefix = data_get($data,'prefix');
        $password = data_get($data,'password');
        for($i=0;$i<$number;$i++){
            $this->genCustomer($prefix,$password);
        }
        return ResponseUtil::success();
    }

    private function genCustomer($prefix,$password){ //创建账号,递归创建
        $username = $prefix . Str::random(8);
        $exists = ChannelCustomer::query()->where('phone',$username)->exists();
        if ($exists){
            $this->genCustomer($prefix,$password);
        }
        $enPassword = Crypt::encryptString($password);
        $data = [
            'phone'=>$username,
            'channel_type'=>4,
            'password'=>$enPassword,
            'created_at'=>now()->format('Y-m-d H:i:s')
        ];
        ChannelCustomer::query()->insert($data);
        return true;
    }

    public function add(){
        {
            DB::beginTransaction();
            try {
                $insert = [];

                $customerDTO = new CustomerDTO($this->request->all());
                $phone = $customerDTO->getPhone();
                $password = $customerDTO->getPassword();

                $insert['phone'] = $phone;
                $insert['mobile'] = $phone;
                $insert['password'] = Crypt::encryptString($password);
                $insert['id'] = getSnowFlakeId();
                $insert['created_at']=date("Y-m-d H:i:s");


                DB::commit();
                ChannelCustomer::query()->insert($insert);
                return ResponseUtil::success();
            } catch (ServiceException $e){
                DB::rollBack();
                throw $e;
            } catch (\Exception $e){
                DB::rollBack();
                throw new ServiceException($e->getMessage());
            }
        }

    }


}
